<template>
    <div>
        <div class="search-content">
            <el-form ref="searchForm" :inline="true" :model="searchContent">
                <el-form-item label="兑换单号：" prop="order_sn">
                    <el-input class="search-content-input" v-model="searchContent.order_sn" placeholder="兑换单号">
                    </el-input>
                </el-form-item>
                <el-form-item label="手机号：" prop="mobile">
                    <el-input class="search-content-input" v-model="searchContent.mobile" placeholder="手机号">
                    </el-input>
                </el-form-item>
                <el-form-item label="承担商家：" prop="store_name">
                    <el-input class="search-content-input" v-model="searchContent.store_name" placeholder="承担商家">
                    </el-input>
                </el-form-item>
                <el-form-item label="兑换时间：" prop="add_time">
                    <el-date-picker v-model="searchContent.add_time" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label prop="order_status">
                    <el-select clearable v-model="searchContent.order_status" placeholder="订单状态">
                        <el-option v-for="item in type_options" :key="item.value_txt" :label="item.value_txt"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label prop="结算">
                    <el-select clearable v-model="searchContent.is_settled" placeholder="结算状态">
                        <el-option value="0" label="未结算"></el-option>
                        <el-option value="1" label="已结算"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button type="primary" @click="resetSearchData">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="search-list">
            <el-table 
                :data="goodsList" border :height="oHeight" :fit="true" header-cell-class-name="hdCellStyle"
                @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="55"></el-table-column>
                <el-table-column align="center" prop="point_ordersn" label="兑换单号" min-width="162" #default="{ row }">
                    <span :class="`color-${row.exception_state}`">{{ row.point_ordersn }}</span>
                    <el-tooltip 
                        class="item" effect="dark" content="异常取消" placement="right-start" v-if="row.exception_state == 1">
                        <i class="el-icon-question color-1" />
                    </el-tooltip>
                </el-table-column>
                <el-table-column align="center" prop="member_mobile" label="手机号" min-width="110"></el-table-column>
                <el-table-column align="center" prop="member_name" label="会员名" min-width="150"></el-table-column>
                <el-table-column align="center" prop="point_truename" label="收件人" min-width="80"></el-table-column>
                <el-table-column align="center" prop="area_address" label="收件地址" min-width="300" show-overflow-tooltip></el-table-column>
                <el-table-column 
                    align="center" prop="point_goodsname" label="商品名称" show-overflow-tooltip min-width="120">
                </el-table-column>
                <el-table-column align="center" prop="pgoods_price" label="商品单价" min-width="70"></el-table-column>
                <el-table-column align="center" prop="point_goodsnum" label="下单数量" min-width="70"></el-table-column>
                <el-table-column align="center" prop="total_price" label="兑换金额" min-width="70"></el-table-column>
                <!-- <el-table-column align="center" prop="member_name" label="会员名" min-width="80"></el-table-column> -->
                <el-table-column align="center" prop="pay_points" label="抵扣积分" min-width="76"></el-table-column>
                <el-table-column align="center" prop="store_owner" label="承担商家" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="capture_point" label="承担积分" min-width="76"></el-table-column>
                <el-table-column align="center" prop="bill_name" label="开票名称" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="add_time" label="下单时间" min-width="150"></el-table-column>
                <el-table-column align="center" label="订单状态" min-width="80" prop="order_status_desc"></el-table-column>
                <el-table-column align="center" prop="settle_desc" label="结算状态" min-width="80"></el-table-column>
                <el-table-column fixed="right" align="center" prop="isInitiative" label="操作" min-width="108">
                    <template slot-scope="scope">
                        <el-button 
                            v-if="scope.row.settle_desc == '未结算'" type="primary"
                            @click="buttonDeal(scope.row.id, scope.row.can_not_operate)">
                            商家结算
                        </el-button>
                        <el-button 
                            v-if="scope.row.is_review != 1 && scope.row.settle_desc == '已结算'" type="danger"
                            @click="billRollback(scope.row.id, scope.row.can_not_operate)">
                            结算撤回
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="bottom">
                <div class="btn-group">
                    <el-button type="primary" class="btn-bottom" @click="expertData">导出检索数据</el-button>
                    <el-button type="primary" class="btn-bottom" @click="oneBill">一键结算</el-button>
                    <el-button type="primary" class="btn-bottom" @click="submitExecl">导入结算</el-button>
                </div>
                <!--分页部分-->
                <div class="paginationOne">
                    <el-pagination 
                        @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="searchContent.currentPage" :page-sizes="[10, 20, 50, 100]"
                        :page-size="searchContent.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
                <!--文件-->
                <el-dialog 
                    title="导入结算" :visible.sync="dialogFormVisible" 
                    class="admin-control-edit" :before-close="handleBeforeClose">
                    <el-upload 
                        style="width: 200px" class="upload-demo" action="#" :auto-upload="false" :limit="1"
                        :on-change="(val, list) => { codeChange(val, list); }" :file-list="codeFileList">
                        <el-button size="primary" type="primary">选择文件</el-button>
                    </el-upload>
                    <el-link 
                        class="tpyeDown" target="_blank"
                        :href='$store.state.location.origin + "/admin/adminImports/index.php?act=pointSettleImport&op=template"'>
                        模板下载
                    </el-link>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submit">提交</el-button>
                        <el-button @click="handleBeforeClose()">取 消</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
import { objScreen } from "@/common/js/util";
export default {
    props: {},
    data() {
        return {
            goodsList: [],
            oHeight: 800,
            searchContent: {
                currentPage: 1,
                pageSize: localStorage.getItem("pageSize") * 1 || 20,
                add_time: "",//时间
                order_sn: "",//订单编号
                member_name: "",//会员名称
                mobile: "",//手机号
                is_settled: "", //是否结算
                review_page: 0,//是否复核页面
                type: 1,//1积分订单 2是在线支付
                store_id: '',//店铺id
                is_review: '',//是否复核
                is_paid: '',//是否已打款
                order_status: '',//订单状态
                store_name: "",
            },
            originate: '',
            dialogFormVisible: false,
            searchObj: {},
            total: 0,
            check: [],
            type_options: [
                // {value: 2, value_txt: "已取消"},
                // {value: 10, value_txt: "已提交,待付款"},
                // {value: 11, value_txt: "已付款,待确认"},
                // {value: 20, value_txt: "确认收款,待发货"},
                { value: 30, value_txt: "已发货,待收货" },
                { value: 40, value_txt: "已完成" },
                // {value: 65, value_txt: "积分已扣,未付款"},
                // {value: 70, value_txt: "已退款"},
                { value: 60, value_txt: "待评价" },
            ],//订单状态
            dialogFormVisible: false,
            codeFileList: [],

        };
    },
    created() {
        // if(this.externalData) {
        // this.searchContent.originate = this.externalData.originate;
        // this.searchObj.originate = this.externalData.originate;
        //     this.searchContent.is_valid = this.externalData.is_valid
        // 		this.searchObj.is_valid = this.externalData.is_valid;
        // }
        this.beforeData();
        this.search();
    },
    methods: {
        // 提交结算
        submitExecl() {
            this.dialogFormVisible = true;
        },
        codeChange(val, list) {
            this.codeFileList = list;
        },
        //上传excel文件
        submit() {
            if (this.codeFileList.length) {
                let data = new FormData();
                data.append("file", this.codeFileList[0].raw);
                this.$http
                    .post(
                        "/admin/adminImports/index.php?act=pointSettleImport&op=run",
                        data
                    )
                    .then((res) => {
                        if (res.code === 1) {
                            this.$message.success(res.msg);
                            this.handleBeforeClose()
                            this.execlErr = res.data;
                            if (this.execlErr.length > 0) {
                                this.$alert(this.execlErr, "错误单号", {
                                    confirmButtonText: "确定",
                                    callback: (action) => { },
                                });
                            }
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.error(err);
                    });
            } else {
                alert("请选择文件");
            }
        },
        handleBeforeClose(done) {
            this.dialogFormVisible = false
            this.codeFileList = []
            typeof done == 'function' && done()
        },
        //获取所有订单状态
        beforeData() {
            // var data = {
            //   page: 1,
            //   pageSize: 99999,
            // };
            // this.$http
            //   .get(`/admin/pointprod/index.php?act=pointOrder&op=stateList`, {
            //     params: data,
            //   })
            //   .then((res) => {
            //     this.type_options = res.data;
            //   })
            //   .catch((err) => {
            //     this.$message.error(err);
            //   });
        },

        // closeIntegral(item) {
        //   let that = this;
        //   this.$confirm("确认关闭？")
        //     .then((res) => {
        //       this.$http
        //         .post("/admin/pointprod/index.php?act=pointOrder&op=closePointOrder", {
        //           pay_ordersn: item.point_ordersn,
        //         })
        //         .then((res) => {
        //           if (res.code == 1) {
        //              this.$message.success(res.msg);
        //             that.getListData(); //刷新列表
        //           } else {
        //             alert(res.msg);
        //           }
        //         });
        //     })
        //     .catch((res) => {
        //       console.log(res);
        //     });
        // },

        // refund(item) {
        //   let that = this;
        //   this.$confirm("确认退款？")
        //     .then((res) => {
        //       this.$http
        //         .post("/admin/bill/index.php?act=commonRefund&op=refund", {
        //           pay_ordersn: item.point_ordersn,
        //         })
        //         .then((res) => {
        //           if (res.code == 1) {
        //             that.getListData(); //刷新列表
        //           } else {
        //             alert(res.msg);
        //           }
        //         });
        //     })
        //     .catch((res) => {
        //       console.log(res);
        //     });
        // },

        //一键结算
        oneBill(type) {
            let idArr = [];
            let dataErr = false;
            if (this.check.length === 0) {
                this.$message.warning("请勾选数据");
                return;
            }
            this.check.forEach((item) => {
                if (item.settle_desc === "未结算") {
                    idArr.push(item.id);
                } else {
                    dataErr = true;
                }
            });
            if (dataErr) {
                this.$message.error("请选择正确的状态数据！");
                return;
            }
            for (var item of this.goodsList) {
                if (idArr.indexOf(item.id) >= 0) {
                    if (item.can_not_operate) {
                        this.$message.error("请选择正确的状态！");
                        return;
                    }
                }
            }
            this.$http.post('/admin/points/index.php?act=PointsSettle&op=quickSettle', { ids: idArr, }).then((res) => {
                if (res.code === 1) {
                    this.$message.success(res.msg);
                    this.search(this.searchContent.currentPage);
                } else {
                    this.$message.warning(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        handleSelectionChange(val) {
            this.check = val;
        },
        //获取列表数据
        getListData() {
            var data = this.searchObj;
            data.page = this.searchContent.currentPage;
            data.pageSize = this.searchContent.pageSize;
            this.$http.get('/admin/points/index.php?act=PointsSettle&op=settleList', { params: data, }).then((res) => {
                if (res.code === 1) {
                    this.total = res.data.totalCount;
                    this.goodsList = res.data.list.map(item => {
                        if (item.point_inner == 1) item.point_inner_checked = true
                        else item.point_inner_checked = false
                        return item
                    })
                    // this.$message.success( res.msg);
                    // this.getListData();
                } else {
                    this.total = 0;
                    this.goodsList = [];
                    this.$message.error(res.msg);
                }
            })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
        //搜索条件汇总
        search(page) {
            this.searchContent.currentPage = Number(page) ? Number(page) : 1;
            let add_time = this.searchContent.add_time;
            this.searchObj = objScreen({
                add_time_begin: add_time[0] ? this.formatDate(add_time[0] * 1000 && parseInt(add_time[0].getTime())) : '',
                add_time_end: add_time[1] ? this.formatDate(add_time[1] * 1000 && parseInt((add_time[1].getTime()))).replace('00:00:00', '23:59:59') : '',
                order_sn: this.searchContent.order_sn,//订单编号
                member_name: this.searchContent.member_name,//会员名称
                mobile: this.searchContent.mobile,//手机号
                order_status: this.searchContent.order_status,//订单状态
                review_page: this.searchContent.review_page,//是否复核页面
                type: this.searchContent.type,//1积分订单 2是在线支付
                store_id: this.searchContent.store_id,//店铺id
                is_settled: this.searchContent.is_settled,//是否结算
                is_review: this.searchContent.is_review,//是否复核
                is_paid: this.searchContent.is_paid,//是否已打款
                store_owner: this.searchContent.store_name,
            });
            this.getListData();
        },
        //重置
        resetSearchData() {
            this.$refs["searchForm"].resetFields();
            this.searchContent.is_bill = "";
            this.searchContent.is_settled = "";
            this.search();
        },
        //导出检索数据
        expertData() {
            var host;
            if (this.$store.state.isServer) {
                host = location.host.replace("admin", "api");
            } else {
                host = location.host + "/api";
            }
            var url =
                location.protocol +
                "//" +
                host +
                "/admin/points/index.php?act=PointsSettle&op=settleList&is_export=1";
            var searchData = this.searchObj;
            for (var key in searchData) {
                if (
                    !(
                        searchData[key] === null ||
                        searchData[key] === "" ||
                        searchData[key] === undefined ||
                        key === "page" ||
                        key === "pageSize" ||
                        key === "currentPage"
                    )
                ) {
                    url += "&" + key + "=" + searchData[key];
                }
            }
            window.location.href = url;
        },
        handleSizeChange(pageSize) {
            localStorage.setItem("pageSize", pageSize);
            this.searchContent.pageSize = pageSize;
            this.searchContent.currentPage = 1;
            this.search();
        },
        handleCurrentChange(page) {
            this.searchContent.currentPage = page;
            this.search(page);
        },
        //结算
        buttonDeal(id, operate) {
            if (operate) {
                this.$message.error('无法操作');
                return false;
            }
            this.$http
                .post("/admin/points/index.php?act=PointsSettle&op=settle", {
                    id: id,
                }).then((res) => {
                    if (res.code === 1) {
                        this.search(this.searchContent.currentPage);
                        this.$message.success(res.msg);
                    } else {
                        this.$message.error(res.msg);
                    }
                }).catch((err) => {
                    this.$message.error(err);
                });
        },
        //撤回结算
        billRollback(id, operate) {
            if (operate) {
                this.$message.error('无法操作');
                return false;
            }
            this.$http
                .post("/admin/points/index.php?act=PointsSettle&op=settleWithdraw", {
                    id: id,
                })
                .then((res) => {
                    if (res.code === 1) {
                        this.search(this.searchContent.currentPage);
                        this.$message.success(res.msg);
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
        formatDate(datetime) {
            var date = new Date(datetime); //datetime时间戳为13位毫秒级别,如为10位需乘1000
            var month = ("0" + (date.getMonth() + 1)).slice(-2),	// getMonth是从1-11,所以需要加1
                sdate = ("0" + date.getDate()).slice(-2),	// -2表示从倒数第二个元素开始截取
                hour = ("0" + date.getHours()).slice(-2),
                minute = ("0" + date.getMinutes()).slice(-2),
                second = ("0" + date.getSeconds()).slice(-2);
            var thatDate = date.getFullYear() + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
            // 返回
            return thatDate;
        }
    },
    mounted() {
        resize(this);
    }
};
</script>
<style lang="scss" scoped>
.color-1 {
    color: #ff3300;
}
.bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.search-content-input {
    width: 200px;
}
.tpyeDown {
    color: #409eff;
    margin-top: 10px;
}
</style>